package com.techwells.learningkites.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SlidingPaneLayout;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.techwells.learningkites.R;
import com.techwells.learningkites.fragment.CourseFragment;
import com.techwells.learningkites.fragment.MyFragment;
import com.techwells.learningkites.fragment.VideoFragment;
import com.techwells.learningkites.model.MainPageViewModel;
import com.techwells.learningkites.model.VideoDetailViewModel;
import com.techwells.learningkites.networkaccess.KitesRequestUrl;
import com.techwells.learningkites.networkservice.KitesServiceMediator;
import com.techwells.learningkites.networkservice.model.VideoCategory;
import com.techwells.taco.base.CommonBaseFragmentActivity;
import com.techwells.taco.mvvm.Route;
import com.techwells.taco.net.HttpConnectionUtils;
import com.techwells.taco.net.HttpHandler;
import com.techwells.taco.networkservice.ServiceMediator;
import com.techwells.taco.tasktool.TaskToken;
import com.techwells.taco.utils.ToastUtils;

public class MainPageActivity extends CommonBaseFragmentActivity implements OnClickListener, OnItemClickListener {
	
	private RadioGroup mainRg;
	private RadioButton rbCourse,rbVideo,rbMy;
	private Fragment[] mFragments;
	private FragmentManager mFragmentManager;
	private FragmentTransaction mFragmentTransaction;
	
	private ImageView ivLeft;
	private TextView titleCenter,titleRight,btnLogout;
	
	private SlidingPaneLayout menu;
	private ListView menuListView;
	private List<Map<String, Object>> menuList;
	private SimpleAdapter menuAdapter;
	
	private MainPageViewModel presentViewModel;
	public static int isRefresh = 0;  //主activity第一次请求判断，课件分集和视频分集
	
	private long lastClickTime;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		initViews();
		initFragments();
	}

	private void initFragments() {
		mFragments = new Fragment[5];
		mFragmentManager = getSupportFragmentManager();
		mFragments[0] = mFragmentManager.findFragmentById(R.id.fragment_course);
		mFragments[1] = mFragmentManager.findFragmentById(R.id.fragment_video);
		mFragments[2] = mFragmentManager.findFragmentById(R.id.fragment_my);
		mFragmentTransaction = mFragmentManager.beginTransaction().hide(mFragments[0])
				.hide(mFragments[1]).hide(mFragments[2]);
		mFragmentTransaction.show(mFragments[0]).commit();
		rbCourse.setChecked(true);
		initTitleBar( getResources().getString(R.string.course), this, this, R.drawable.menu, 0);
		mainRg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				mFragmentTransaction = mFragmentManager.beginTransaction().hide(mFragments[0])
						.hide(mFragments[1]).hide(mFragments[2]);
				switch (checkedId) {
				case R.id.tab_rb_course:
					mFragmentTransaction.show(mFragments[0]).commit();
					break;
				case R.id.tab_rb_video:
					mFragmentTransaction.show(mFragments[1]).commit();
					break;
				case R.id.tab_rb_my:
					mFragmentTransaction.show(mFragments[2]).commit();
					break;


				default:
					break;
				}
				
				initTitles(checkedId);
				
			}

			

		});
		
	}
	
	private void initTitles(int chechedId) {
		switch (chechedId) {
		case R.id.tab_rb_course:
			titleCenter.setText(getResources().getString(R.string.course));
			titleRight.setVisibility(View.GONE);
			break;
		case R.id.tab_rb_video:
			titleCenter.setText(getResources().getString(R.string.video));
			titleRight.setVisibility(View.GONE);
			break;
		case R.id.tab_rb_my:
			titleCenter.setText(getResources().getString(R.string.my));
			titleRight.setText(getResources().getString(R.string.edit));
			titleRight.setVisibility(View.VISIBLE);
			break;

		default:
			break;
		}
		
	}

	private void initViews() {
		ivLeft=(ImageView)findViewById(R.id.common_activity_title_left_image);
		titleCenter = (TextView) findViewById(R.id.common_activity_title_middle_tv);
		titleRight = (TextView) findViewById(R.id.common_activity_title_right_tv);
		titleRight.setOnClickListener(this);
		
		menu = (SlidingPaneLayout) findViewById(R.id.menu);
		menu.setSliderFadeColor(getResources().getColor(android.R.color.transparent));
		menuListView = (ListView) findViewById(R.id.list_menu);
		menuList = new ArrayList<Map<String,Object>>();
		
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("img", R.drawable.myaccount);
		map.put("str", getResources().getString(R.string.myaccount));
		menuList.add(map);
		map = new HashMap<String, Object>();
		map.put("img", R.drawable.pay);
		map.put("str", getResources().getString(R.string.pay));
		menuList.add(map);
		map = new HashMap<String, Object>();
		map.put("img", R.drawable.setting);
		map.put("str", getResources().getString(R.string.setting));
		menuList.add(map);
		map = new HashMap<String, Object>();
		map.put("img", R.drawable.about);
		map.put("str", getResources().getString(R.string.about));
		menuList.add(map);
		map = new HashMap<String, Object>();
		map.put("img", R.drawable.feedback);
		map.put("str", getResources().getString(R.string.feedback));
		menuList.add(map);
		map = new HashMap<String, Object>();
		map.put("img", R.drawable.share);
		map.put("str", getResources().getString(R.string.share));
		menuList.add(map);
		map = new HashMap<String, Object>();
		map.put("img", R.drawable.clear);
		map.put("str", getResources().getString(R.string.clear));
		menuList.add(map);
		
		menuAdapter = new SimpleAdapter(this, menuList, R.layout.item_menulist, new String[]{"img","str"},
				new int[]{R.id.menu_img,R.id.menu_str});
		menuListView.setAdapter(menuAdapter);
		menuListView.setOnItemClickListener(this);
		
		btnLogout = (TextView) findViewById(R.id.log_out);
		btnLogout.setOnClickListener(this);
		
		mainRg = (RadioGroup) findViewById(R.id.main_rg);
		rbCourse = (RadioButton) findViewById(R.id.tab_rb_course);
		rbVideo = (RadioButton) findViewById(R.id.tab_rb_video);
		rbMy = (RadioButton) findViewById(R.id.tab_rb_my);
	}

	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.common_activity_title_left_image:
			menu.openPane();
			break;
		case R.id.common_activity_title_right_tv:
			if (titleRight.getText().toString() == getResources().getString(R.string.edit)) {
				Route.route().nextController(this, SettingUserInfoActivity.class.getName(), Route.WITHOUT_RESULTCODE);
			}
			break;
		case R.id.log_out:
			doRequestLogout();
			
			break;

		default:
			break;
		}
		
	}

	

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int positon, long id) {
		// TODO Auto-generated method stub
////		ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
////		parameters.add(new BasicNameValuePair("videoId", "113"));
//		ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
//		parameters.add(new BasicNameValuePair("", ""));
//		new HttpConnectionUtils(getFavoriteVideoHandler).get(KitesRequestUrl.GET_FAVORITE_VIDEOS);
		switch (positon) {
		case 1:
			Route.route().nextController(MainPageActivity.this, PayActivity.class.getName(), Route.WITHOUT_RESULTCODE);
			break;
		case 4:
			Route.route().nextController(MainPageActivity.this, FeedbackActivity.class.getName(), Route.WITHOUT_RESULTCODE);
			break;

		default:
			break;
		}
		
	}
	
	@Override
	public void alreadyBindBaseViewModel() {
		// TODO Auto-generated method stub
		super.alreadyBindBaseViewModel();
		
		presentViewModel = (MainPageViewModel) baseViewModel;
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		if (isRefresh < 3) {
			doRequestVideoCategories();
			doRequestCourseCategories();
			doRequestGetProfile();
		}
			
		
	}
	
	private void doRequestGetProfile() {
		doTask(KitesServiceMediator.SERVICE_GET_PROFILE, null);

	}

	private void doRequestLogout() {
		doTask(KitesServiceMediator.SERVICE_DO_LOGOUT,null);
		
	}

	private void doRequestCourseCategories() {
		doTask(KitesServiceMediator.SERVICE_GET_COURSES_CATEGORIES,null);
	}

	private void doRequestVideoCategories() {
		doTask(KitesServiceMediator.SERVICE_GET_VIDEOS_CATEGORIES,null);
	}

	
	@Override
	public void refreshData(TaskToken token) {
		// TODO Auto-generated method stub
		super.refreshData(token);
		
		String method = token.method;
		if (method.equals(KitesServiceMediator.SERVICE_GET_VIDEOS_CATEGORIES) || method.equals(KitesServiceMediator.SERVICE_GET_CATEGORY_VIDEOS)) {
			VideoFragment fragment = (VideoFragment) mFragments[1];
			fragment.refreshData(token);
		}else if (method.equals(KitesServiceMediator.SERVICE_GET_COURSES_CATEGORIES) || method.equals(KitesServiceMediator.SERVICE_GET_COURSES) ) {
			CourseFragment fragment = (CourseFragment) mFragments[0];
			fragment.refreshData(token);
		}else if (method.equals(KitesServiceMediator.SERVICE_DO_LOGOUT)) {
			int returnCode = ((MainPageViewModel) baseViewModel).returnCode;
			if (returnCode == ServiceMediator.Service_Return_Success) {
				isRefresh = 0;
				ToastUtils.show(this, "退出成功");
				finish();
				Route.route().nextController(this, LoginActivity.class.getName(), Route.WITHOUT_RESULTCODE);
			}
		}else if (method.equals(KitesServiceMediator.SERVICE_GET_PROFILE)){
			MyFragment fragment = (MyFragment) mFragments[2];
			fragment.refreshData(token);
		}
				
	}
	
	
	@Override
	public void onBackPressed() {
		if (lastClickTime<=0) {
			Toast.makeText(this, "再按一次后退键退出应用", Toast.LENGTH_SHORT).show();
			lastClickTime = System.currentTimeMillis();
		}else{
			long currentClickTime = System.currentTimeMillis();
			if (currentClickTime-lastClickTime<1000) {
				isRefresh = 0;
				finish();
			}else{
				Toast.makeText(this, "再按一次后退键退出应用", Toast.LENGTH_SHORT).show();
				lastClickTime = currentClickTime;
			}
		}
	}
	
}
